package com.voxel.sense.infomsg.module.trace.details;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ClockInMarkerBean;
import com.voxel.sense.infomsg.module.common.VRecyclerActivity;
import com.voxel.sense.infomsg.module.trace.map.CheckinsRecordActivity;
import com.voxel.sense.infomsg.utils.GPSUtils;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.response.ClockInsDetailsEntity;
import cyy.example.com.facotry.model.api.response.HistoryDataEntity;

/**
 * Created by ChenYiYao on 2018/10/18.
 * des : 打开记录详情
 */
public class CheckinsDetailsActivity extends VRecyclerActivity<CheckinsDetailsContract.Presenter, HistoryDataEntity>
        implements CheckinsDetailsContract.View<HistoryDataEntity> {
    @BindView(R.id.titlebar)
    TextTitleBar titleBar;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.tv_start_time)
    TextView tv_start_time;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.recycle_view)
    RecyclerView recycle_view;
    @BindView(R.id.appbar_layout)
    AppBarLayout appbar_layout;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;

    TimePickerView mPickerView; //时间选择器
    RecyclerAdapter mAdapteraa;
    private String mSId;

    public static final String START_TIME = "START_TIME";
    public static final String END_TIME = "END_TIME";
    private String mName;

    public static void show(Context context, String id, String name) {
        show(context, id, name, null, null);
    }

    /**
     * @param id
     * @param startTime 可供查询时间段的开始时间
     * @param endTime   可供查询时间段的结束时间
     */
    public static void show(Context context, String id, String name, Date startTime, Date endTime) {
        Intent intent = new Intent(context, CheckinsDetailsActivity.class);
        if (startTime != null && endTime != null && (startTime.getTime() < endTime.getTime())) {
            intent.putExtra(START_TIME, startTime);
            intent.putExtra(END_TIME, endTime);
        }
        intent.putExtra(IntentConstants.STRING_ID, id);
        intent.putExtra(IntentConstants.STRING_NAME, name);
        context.startActivity(intent);
    }

    @Override
    protected CheckinsDetailsContract.Presenter initPresenter() {
        return new CheckinsDetailsPresenter(this);
    }

    @Override
    public RecyclerAdapter getRecyclerViewAdapter() {
        return mAdapteraa;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_checkins_details;
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (TextUtils.isEmpty(getIntent().getStringExtra(IntentConstants.STRING_ID)))
            return false;

        return super.initArgs(bundle);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        initPickTimeView();
    }

    @Override
    protected void initData() {
        super.initData();
        titleBar.setTitleText("打开详情");

        mSId = getIntent().getStringExtra(IntentConstants.STRING_ID);
        mName = getIntent().getStringExtra(IntentConstants.STRING_NAME);
        refresh_layout.setDisableContentWhenLoading(true);
        refresh_layout.setEnableLoadMoreWhenContentNotFull(false);

        empty_view.setRefreshBtnVisible(false);

        mAdapteraa = new CheckInsTimeListAdapter();
        recycle_view.addItemDecoration(new ClockInDetItemDivider(R.drawable.recycle_divider_1dp_pink));
        recycle_view.setLayoutManager(new LinearLayoutManager(this));
        recycle_view.setAdapter(mAdapteraa);
        refresh_layout.autoRefresh();

        //默认加载当月的数据
        Date start = new Date(System.currentTimeMillis());
        Date lastDayOfMonth = TimeUtils.getFirstDayDateOfMonth(start);
        tv_start_time.setText(TimeUtils.date2String(lastDayOfMonth, new SimpleDateFormat(Constants.TimeYMDFormat)));
        tv_end_time.setText(TimeUtils.date2String(start, new SimpleDateFormat(Constants.TimeYMDFormat)));
    }

    @Override
    protected void initEven() {
        super.initEven();
        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadMore();
            }
        });
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                String start = tv_start_time.getText().toString();
                String end = tv_end_time.getText().toString();
                mPresenter.doRefresh(mSId, start, end);
            }
        });

        mAdapteraa.setListener(new RecyclerAdapter.AdapterListenerImpl() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, Object data) {
                super.onItemClick(holder, data);
                if (data != null && data instanceof ClockInsDetailsEntity.CoordinateListBean.ValuesBean) {
                    ClockInsDetailsEntity.CoordinateListBean.ValuesBean bean = (ClockInsDetailsEntity.CoordinateListBean.ValuesBean) data;
                    try {
                        double v = Double.parseDouble(bean.getLatitude());
                        double v1 = Double.parseDouble(bean.getLongitude());
                        double[] doubles = GPSUtils.bd09_To_Gcj02(v, v1);
                        //某个时间点的item
                        CheckinsRecordActivity.show(CheckinsDetailsActivity.this, mSId, mName, bean.getTime(), doubles[0], doubles[1], false);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                } else if (data != null && data instanceof ClockInsDetailsEntity.CoordinateListBean) {
                    //某天的item
                    mPresenter.doHandlerItemEvent(data,mSId,mName);
                }
            }
        });
    }

    @Override
    public void onRefreshFinish() {
        super.onRefreshFinish();
        //有可能在刷新的时候，滑动隐藏AppBarLayout，若这时显示空界面。AppBarLayout则无法再通过滑动显示。这时需强制显示
        //改变代码就是强行回到初始位置
        CoordinatorLayout.Behavior coordbehavior = ((CoordinatorLayout.LayoutParams) appbar_layout.getLayoutParams()).getBehavior();
        if (mAdapteraa.getItemCount() <= 0 && coordbehavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) coordbehavior;
            int topAndBottomOffset = behavior.getTopAndBottomOffset();
            if (topAndBottomOffset != 0) {
                behavior.setTopAndBottomOffset(0);

            }
        }
    }

    /**
     * 初始化时间选择器
     */
    private void initPickTimeView() {
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();
        Date start = (Date) getIntent().getSerializableExtra(START_TIME);
        Date end = (Date) getIntent().getSerializableExtra(END_TIME);
        if (start != null) {
            //获取传入的开始时间
            startCalendar.setTime(start);
            endCalendar.setTime(end);
        } else {
            //初始化选择器的时间
            startCalendar.set(Calendar.DATE, 1);
            startCalendar.set(Calendar.MONTH, 0);
        }
        mPickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                onCoverTime(date, v);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})//分别表示是否显示年，月，日，时，分，秒，默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setDate(startCalendar)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startCalendar, endCalendar)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
    }

    private void onCoverTime(Date date, View v) {
        //        转换时间格式
        String string = TimeUtils.date2String(date, new SimpleDateFormat(Constants.TimeYMDFormat));
        if (v.getId() == R.id.tv_start_time) {
            tv_start_time.setText(string);
        } else if (v.getId() == R.id.tv_end_time) {
            tv_end_time.setText(string);
        }
    }


    @OnClick({R.id.tv_start_time, R.id.tv_end_time, R.id.btn_search})
    public void onClickEvent(View v) {
        switch (v.getId()) {
            case R.id.tv_start_time:
                mPickerView.show(tv_start_time);
                break;
            case R.id.tv_end_time:
                mPickerView.show(tv_end_time);
                break;
            case R.id.btn_search:
                refresh_layout.autoRefresh();
                break;
        }
    }

    @Override
    public void onSkipMap(List<ClockInMarkerBean> data) {
        CheckinsRecordActivity.show(this, (ArrayList<ClockInMarkerBean>) data,false);
    }
}
